#!/usr/bin/python3
# -*- encoding: utf-8 -*-
'''
@File        :爬虫学习.py
@Time        :2020/09/13 16:53:06
@Author      :He
@Software    :vsCode
'''

from hashlib import md5
import requests
import os
from pyppeteer import launch
# from pyppeteer import coroutine

import asyncio
from pyppeteer import launcher
import time
import random
from PIL import Image


class Chaojiying_Client(object):
    def __init__(self, username, password, soft_id):
        self.username = username
        password = password.encode('utf8')
        self.password = md5(password).hexdigest()
        self.soft_id = soft_id
        self.base_params = {
            'user': self.username,
            'pass2': self.password,
            'softid': self.soft_id,
        }
        self.headers = {
            'Connection':
            'Keep-Alive',
            'User-Agent':
            'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)',
        }

    def PostPic(self, im, codetype):
        """
        im: 图片字节
        codetype: 题目类型 参考 http://www.chaojiying.com/price.html
        """
        params = {
            'codetype': codetype,
        }
        params.update(self.base_params)
        files = {'userfile': ('ccc.jpg', im)}
        r = requests.post('http://upload.chaojiying.net/Upload/Processing.php',
                          data=params,
                          files=files,
                          headers=self.headers)
        return r.json()

    def ReportError(self, im_id):
        """
        im_id:报错题目的图片ID
        """
        params = {
            'id': im_id,
        }
        params.update(self.base_params)
        r = requests.post(
            'http://upload.chaojiying.net/Upload/ReportError.php',
            data=params,
            headers=self.headers)
        return r.json()


async def main():

    # hook  禁用 防止监测webdriver
    launcher.DEFAULT_ARGS.remove("--enable-automation")

    launch_args = {
        "headless": False,
        "args": [
            "--start-maximized",
            "--no-sandbox",
            "--disable-infobars",
            "--ignore-certificate-errors",
            "--log-level=3",
            "--enable-extensions",
            "--window-size=1920,1080",
            "--user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36",
        ],
    }
    browser = await launch(**launch_args)

    page = await browser.newPage()

    # 设置窗口大小
    await page.setViewport({"width": 1920, "height": 1040})
    await page.goto('http://cpquery.cnipa.gov.cn')
    await asyncio.sleep(3)

    await page.click('#selectyzm_text')
    await asyncio.sleep(2)

    # 截取一张图片
    # options = {'path': 'verificationCode.png'}
    # clip = {'x': 1050, 'y': 230, 'width': 315, 'height': 255}
    # options['clip'] = clip
    # await page.screenshot(options)

    # 截取一张图片
    await page.screenshot({'path': 'verificationCode.png'})
    await asyncio.sleep(2)

    img = Image.open("verificationCode.png")
    cropped = img.crop((1030, 220, 1350, 480))  # (left, upper, right, lower) 左上，右下
    # Image._show(cropped)
    cropped.save("pil_cut_thor.png")

    # codeDict = {'err_no': 0, 'err_str': 'OK', 'pic_id': '3116823524718600008', 'pic_str': '239,65|113,82|246,123', 'md5': '53b749f6ff726ab4d92d982690a8fa84'}
    # if codeDict['err_no'] == 0:
    #     print(codeDict['pic_str'])

    #     codeList = codeDict['pic_str'].split('|')
    #     print(codeList)

    #     for code in codeList:
    #         stop = random.uniform(2, 3)
    #         time.sleep(stop)

    #         x = int(code.split(',')[0]) + 1030
    #         y = int(code.split(',')[1]) + 220
    #         await page.mouse.click(x, y)

    # # await page.click('#selectyzm_text')

    # # await page.mouse.click(1130, 300)
    # # await page.mouse.click(1013, 337)
    # # await page.mouse.click(1093, 959, {'button': 'left', 'clickCount': 1})
    # # await page.mouse.click(1093, 959, {'button': 'left', 'clickCount': 1})

    chaojiying = Chaojiying_Client('h521822', 'hj123456', '794d92b4ae80aff7b183e1c6c260d553')  # 用户中心>>软件ID 生成一个替换 96001
    im = open('pil_cut_thor.png', 'rb').read()  # 本地图片文件路径 来替换 a.jpg 有时WIN系统须要//
    codeDict = chaojiying.PostPic(im, 9103)    # 1902 验证码类型  官方网站>>价格体系 3.4+版 print 后要加()
    print(codeDict)

    # codeDict = {'err_no': 0, 'err_str': 'OK', 'pic_id': '9116721154718600004', 'pic_str': '929,928|1013,930|1093,959', 'md5': 'b140e4158f60eeef02b8b22e08f67032'}
    # j = s.json()
    if codeDict['err_no'] == 0:
        print(codeDict['pic_str'])

        codeList = codeDict['pic_str'].split('|')
        print(codeList)

        for code in codeList:
            stop = random.uniform(2, 3)
            time.sleep(stop)
            x = int(code.split(',')[0]) + 1030
            y = int(code.split(',')[1]) + 220

            await page.mouse.click(x, y)

    # #         await page.click('#selectyzm_text')

    # #         coroutine click(x:float,y:float,options:dict = None,** kwargs )

    # # await page.evaluate('''() =>{ Object.defineProperties(navigator,{ webdriver:{ get: () => false } }) }''')
    await asyncio.sleep(20)


if __name__ == "__main__":
    os.chdir(os.path.abspath(os.path.dirname(__file__)))
    asyncio.get_event_loop().run_until_complete(main())
